/**
 * 
 */
package org.seckill.service.impl;

import java.util.Date;
import java.util.List;

import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessSeckilledDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entry.Seckill;
import org.seckill.entry.SuccessSeckilled;
import org.seckill.enums.SeckillStateEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * 
 * @author yue
 * 2016年5月29日 上午11:19:31
 */
@Service
public class SeckillServiceImpl implements SeckillService{
	private final Logger logger =  LoggerFactory.getLogger(getClass());	
	
	@Autowired
	private SeckillDao seckillDao;
	@Autowired
	private SuccessSeckilledDao successSeckilledDao;
	//混淆MD5,密钥
	private final String slat = "dq%^&(cdsiveuve82910ncjdis>:KIOP(";
	/* 
	 * @return 
	 */
	@Override
	public List<Seckill> getSeckillList() {
		logger.info("默认查询5条");
		return seckillDao.queryAll(0, 5);
	}

	/* 
	 * @param seckillId
	 * @return 
	 */
	@Override
	public Seckill getById(long seckillId) {
		return seckillDao.queryById(seckillId);
	}

	/* 
	 * @param seckillId
	 * @return 
	 */
	@Override
	public Exposer exportSeckillUrl(long seckillId) {
		Seckill seckill = getById(seckillId);
		if(seckill == null){
			return new Exposer(false, seckillId);
		}
		Date startTime = seckill.getStartTime();
		Date endTime = seckill.getEndTime();
		Date nowTime = new Date();
		if(nowTime.before(startTime) || nowTime.after(endTime)){
			return new Exposer(false,seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
		}
		String md5 = getMd5(seckillId);
		return new Exposer(true, md5, seckillId);
	}

	/**
	 * 获取MD5
	 * @param seckillId
	 * @return
	 */
	private String getMd5(long seckillId) {
		String base = seckillId +"/"+slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		logger.info("md5:"+md5);
		return md5;
	}

	/* 执行秒杀
	 * @param seckillId
	 * @param userPhone
	 * @param md5
	 * @return 
	 */
	@Override
	@Transactional
	public SeckillExecution executeSeckill(long seckillId, long userPhone,
			String md5) {
		if(md5 == null || !md5.equals(getMd5(seckillId))){
			throw new SeckillException("秒杀数据被篡改！");
		}
		try {
			//执行秒杀逻辑：减库存+记录购买行为
			Date killTime = new Date();
			int reduceNum = seckillDao.reduceNumber(seckillId, killTime);
			if(reduceNum <= 0){
				throw new SeckillCloseException("秒杀已结束！");
			}
			//记录购买行为
			int insertNum = successSeckilledDao.insertSuccessSeckilled(seckillId, userPhone);
			if(insertNum <= 0){
				//重复秒杀
				throw new RepeatKillException("重复秒杀！");
			}
			SuccessSeckilled successSeckilled = successSeckilledDao.queryByIdWithSeckill(seckillId);
			return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successSeckilled) ;
		}catch(SeckillCloseException ce){
			throw ce;
		}catch(RepeatKillException ke){
			throw ke;
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			//所有编译期异常转化为运行期异常
			throw new SeckillException("秒杀异常："+e.getMessage());
		}
	}

}
